//
//  LoginViewController.m
//  TengyunStation
//
//  Created by Johnny on 15/8/24.
//  Copyright (c) 2015年 xingrong. All rights reserved.
//

#import "LoginViewController.h"
#import "SocketRequest.h"
#import "Singleton.h"
#import "ForgetPwdViewController.h"
#import "UIImage+UIColor.h"
#import "RecieveAlertView.h"
#import "MobClick.h"
#import "AFHttpService.h"

#define SaveLoginTelephone      @"logintelephone"

@interface LoginViewController ()<SocketRequestDelegate> {
    SocketRequest *_socketRequest;
}

@end

@implementation LoginViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        _socketRequest = [[SocketRequest alloc] initWithSocketRequestDelegate:self];
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:NSStringFromClass([self class])];
    NSString *telephone = [[NSUserDefaults standardUserDefaults] objectForKey:SaveLoginTelephone];
    _telephoneTextField.text = telephone;
    self.navigationController.navigationBarHidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:NSStringFromClass([self class])];
    self.navigationController.navigationBarHidden = NO;
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    }
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    if (!iPhone5Later) {
        _logoImageView.frame = CGRectMake(_logoImageView.frame.origin.x, 40, _logoImageView.frame.size.width, _logoImageView.frame.size.height);
        _inputView.frame = CGRectMake(_inputView.frame.origin.x, 180, _inputView.frame.size.width, _inputView.frame.size.height);
        _loginBtn.frame = CGRectMake(_loginBtn.frame.origin.x, 280, _loginBtn.frame.size.width, _loginBtn.frame.size.height);
        _fogetBtn.frame = CGRectMake(_fogetBtn.frame.origin.x, 320, _fogetBtn.frame.size.width, _fogetBtn.frame.size.height);
    }
    _inputView.layer.borderColor = LineColor.CGColor;
    _inputView.layer.borderWidth = 0.5;
    UILabel *line = [[UILabel alloc] initWithFrame:CGRectMake(60, 43.5, 260, 0.5)];
    line.backgroundColor = LineColor;
    [_inputView addSubview:line];
    [_telephoneTextField addTarget:self action:@selector(textFieldEditingChanged:) forControlEvents:UIControlEventEditingChanged];
    [_passwordTextField addTarget:self action:@selector(textFieldEditingChanged:) forControlEvents:UIControlEventEditingChanged];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showKeyboard:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hideKeyboard:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

- (void)textFieldEditingChanged:(UITextField *)textField {
    if (textField == _telephoneTextField) {
        if (textField.text.length >= 11) {
            textField.text = [textField.text substringToIndex:11];
            [_passwordTextField becomeFirstResponder];
        }
    } else if (textField == _passwordTextField) {
        if (textField.text.length > PwdMaxLength) {
            
        }
    }
}

- (void)getUserModel {
    [ToastActivity makeActivity:@"加载中..." InView:self.view];
    [[AFHttpService shareInstance] POST:@"/dispatchplatform/getSiteUserInfo" Dictionary:@{@"userTel":CheckString(_telephoneTextField.text)} success:^(ResponseHeader *response) {
        if (response.code == 0) {
            CityModel *cityModel = [CityModel objectWithKeyValues:response.content];
            [Singleton shareInstance].cityModel = cityModel;
            [self loginSocket];
        } else {
            [ToastActivity makeError:response.msg InView:self.view];
        }
    } failure:^(NSString *errorMsg) {
        [ToastActivity makeError:errorMsg InView:self.view];
    }];
}

#pragma mark Notification
- (void)showKeyboard:(NSNotification *)notification {
    [UIView animateWithDuration:0.25 animations:^{
        self.view.frame = CGRectMake(self.view.frame.origin.x, - 80, self.view.frame.size.width, self.view.frame.size.height);
    }];
}

- (void)hideKeyboard:(NSNotification *)notification {
    [UIView animateWithDuration:0.25 animations:^{
        self.view.frame = CGRectMake(self.view.frame.origin.x, 0, self.view.frame.size.width, self.view.frame.size.height);
    }];
}

#pragma mark UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (textField == _telephoneTextField) {
        NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:TelephoneLimit] invertedSet];
        NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
        if (![string isEqualToString:filtered]) {
            return NO;
        }
    }
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField.returnKeyType == UIReturnKeyNext) {
        [_passwordTextField becomeFirstResponder];
    } else {
        [_passwordTextField resignFirstResponder];
    }
    return YES;
}

#pragma mark SocketRequestDelegate
- (void)socket:(GCDAsyncSocket *)socket Code:(NSString *)code Msg:(NSString *)msg Data:(NSData *)data {
    if ([code isEqualToString:SuccessSocket]) {
        [ToastActivity dismissInView:self.view];
        [[NSUserDefaults standardUserDefaults] setObject:_telephoneTextField.text forKey:SaveLoginTelephone];
        [[NSUserDefaults standardUserDefaults] synchronize];
        Usermessage *userMessage = [[Usermessage alloc] initWithData:data Telephone:_telephoneTextField.text];
        [userMessage save];
        [Singleton shareInstance].userMessage = userMessage;
        [[NSNotificationCenter defaultCenter] postNotificationName:@"LoginSuccess" object:nil];
    } else {
        [ToastActivity dismissInView:self.view];
        [DSToast showText:msg InView:self.view];
    }
}

- (void)socket:(GCDAsyncSocket *)socket Msg:(NSString *)msg {
    [ToastActivity dismissInView:self.view];
    [DSToast showText:msg InView:self.view];
}

- (IBAction)loginAction:(id)sender {
    [self.view endEditing:YES];
    if (_telephoneTextField.text.length <= 0) {
        [DSToast showText:@"请输入手机号" InView:self.view];
    } else if (_telephoneTextField.text.length != 11 || ![_telephoneTextField.text hasPrefix:@"1"]) {
        [DSToast showText:@"请输入正确的11位手机号" InView:self.view];
    } else if (_passwordTextField.text.length <= 0) {
        [DSToast showText:@"请输入密码" InView:self.view];
    } else {
        [self getUserModel];
    }
}

- (void)loginSocket {
    NSMutableData *mutableData = [[NSMutableData alloc] initWithData:[SocketMethod socketHeadDataMethod:@"STU1"]];
    [mutableData appendBytes:[SocketMethod checkLegal:_telephoneTextField.text] length:16];
    [mutableData appendBytes:[SocketMethod checkLegal:_passwordTextField.text] length:128];
    [mutableData appendBytes:[SocketMethod checkLegal:@""] length:64];
    [_socketRequest addSocketData:mutableData SocketTag:0];
}

- (IBAction)forgetPassword:(id)sender {
    ForgetPwdViewController *forgetPVC = [[ForgetPwdViewController alloc] initWithNibName:@"ForgetPwdViewController" bundle:nil];
    [self.navigationController pushViewController:forgetPVC animated:YES];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    _socketRequest = nil;
}

@end
